package br.com.opet.DAO;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import br.com.opet.vo.*;

public class FotoDAO {
	public static boolean insert(Foto foto)
	{
		try{
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.persist(foto);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
	
	public static Foto SearchById(int idFoto)
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Foto where id = :idP");
			q.setParameter("idP", idFoto);
			List<Foto> fotos = q.getResultList();
			if(!fotos.isEmpty()){
				return fotos.get(0);								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	
	
	public static List<Foto> listAll()
	{
		try
		{
			EntityManager manager = EntityManagerFactory.getInstance();
			Query q = manager.createQuery("from Foto order by id");
			List<Foto> fotos = q.getResultList();
			if(!fotos.isEmpty()){
				return fotos;								
			}
			else
			{
				return null;
			}
		}
		catch(Exception e)
		{
			return null;
		}		
	}
	
	public static boolean remove(int idFoto)
	{
		try{
			Foto foto = SearchById(idFoto);		
			EntityManager manager = EntityManagerFactory.getInstance();
			manager.getTransaction().begin();
			manager.remove(foto);
			manager.getTransaction().commit();
			return true;			
		}
		catch(Exception e){
			return false;
		}
	}
}
